import * as XLSX from "xlsx";
import editStore from "@/store/editStore";
import { getGUID } from "@/utils/index";
import { Label } from "@/views/editFormula/materialList/material/label";
import { ProLabel } from "@/views/editFormula/materialList/material/proLable";
import { Humidity } from "@/views/editFormula/materialList/material/humidity";
import { Desiccant } from "@/views/editFormula/materialList/material/desiccant";
import getEnvConfig from "@/config/axios/getEnvConfig";
/*
  用于解析excel模板文件，将数据存入store中
  支持多sheet，每个sheet对应一个配方
  excel填写要求 详见excel模板文件中红色标注的内容
*/
export default function useExcel(response, uploadFile) {
  return new Promise((resolve, reject) => {
    const store = editStore();
    store.$reset();
    let result = [];
    const fileReader = new FileReader();
    fileReader.readAsArrayBuffer(response.raw);
    fileReader.onload = (ev) => {
      try {
        const data = ev.target.result;
        const workbook = XLSX.read(data, {
          type: "binary",
        });
        const sheet = Object.keys(workbook.Sheets);
        if (sheet.length == 0) {
          throw new Error("文件内容为空");
        }
        for (let s of sheet) {
          let jsonStore = JSON.parse(JSON.stringify(store.$state));
          jsonStore.id = getGUID();
          let jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[s], {
            header: 1,
          });
          if (jsonData.length == 0) {
            continue;
          }
          if (jsonData[0][0] != "配方信息") {
            throw new Error("请检查模板文件是否正确");
          }

          let recipe = jsonStore.recipe;
          recipe.deviceCode = jsonData[1][1];
          recipe.recipeName = jsonData[1][2];
          recipe.recipeNo = jsonData[1][3];
          recipe.version = jsonData[1][4];
          recipe.customerCode = jsonData[1][5];
          recipe.productModel = jsonData[1][6];
          recipe.packingCode = jsonData[1][7];
          recipe.packingLabelCode = jsonData[1][8];
          recipe.formFactor = jsonData[1][9];
          recipe.hasReelcombine = toBool(jsonData[1][10]);
          recipe.inOrderEnale = toBool(jsonData[1][11]);
          //#region  卷盘数据
          let reelConfig = jsonStore.reelConfig;
          reelConfig.reelDesc = jsonData[3][1];
          reelConfig.reelCode = jsonData[3][2];
          reelConfig.reelDiameter = jsonData[3][3];
          reelConfig.reelThickness = jsonData[3][4];
          reelConfig.reelType = jsonData[3][5];
          reelConfig.baseQuantity = jsonData[3][6];
          reelConfig.traceLabel = toBool(jsonData[3][7]);
          reelConfig.traceLabelSide = toPosition(jsonData[3][8]);
          reelConfig.protectiveTapeCode = jsonData[3][9];
          reelConfig.maskingTapeCode = jsonData[3][10];
          reelConfig.beltCode = jsonData[3][11];
          reelConfig.scattered = toScattered(jsonData[3][12]);
          reelConfig.frontImg = toImg(jsonData[3][13]);
          reelConfig.oppositeImg = toImg(jsonData[3][14]);
          //#endregion
          //卷盘物料
          let reelList = jsonStore.reelList[0];
          let packageConfig = jsonStore.packageConfig;
          let innerBox = jsonStore.innerBox;
          let col1 = null;
          let col2 = null;

          for (let i = 4; i < jsonData.length; i++) {
            if (jsonData[i][0] == "卷盘物料") {
              col1 = 0;
            } else if (jsonData[i][0] == "包装袋信息") {
              col1 = 1;
              continue;
            } else if (jsonData[i][0] == "包装袋物料") {
              col1 = 2;
            } else if (jsonData[i][0] == "内盒信息") {
              col1 = 3;
            } else if (jsonData[i][0] == "内盒物料") {
              col1 = 4;
            }
            if (jsonData[i][1] == "产品标签") {
              col2 = 0;
              continue;
            } else if (jsonData[i][1] == "辅助标签") {
              col2 = 1;
              continue;
            } else if (jsonData[i][1] == "湿度卡") {
              col2 = 2;
              continue;
            } else if (jsonData[i][1] == "干燥剂") {
              col2 = 3;
              continue;
            }
            //continue 表示当前行是文本数据 跳到下一行
            //未填写料号 跳过该行数据
            if (col1 == 0) {
              if (!jsonData[i][2]) {
                continue;
              }
              //卷盘物料
              if (col2 == 0) {
                //标签信息
                let label = parseLable(jsonData, i);
                if (jsonData[i][4] == "正面") {
                  reelList.frontComponentList.push(label);
                } else if (jsonData[i][4] == "反面") {
                  reelList.oppositeComponentList.push(label);
                }
              } else if (col2 == 1) {
                //辅助标签
                let prolabel = parseProlabel(jsonData, i);
                if (jsonData[i][4] == "正面") {
                  reelList.frontComponentList.push(prolabel);
                } else if (jsonData[i][4] == "反面") {
                  reelList.oppositeComponentList.push(prolabel);
                }
              } else if (col2 == 2) {
                //湿度卡
                let humidity = new Humidity();
                humidity.code = jsonData[i][2];
                humidity.position = toPosition(jsonData[i][3]);
                humidity.length = jsonData[i][4];
                humidity.width = jsonData[i][5];
                humidity.x = jsonData[i][6];
                humidity.y = jsonData[i][7];
                humidity.angle = jsonData[i][8];
                humidity.humidityType = jsonData[i][9];
                humidity.humidityColor = jsonData[i][10];
                humidity.humidityColorHeight = jsonData[i][11];
                humidity.picName = toImg(jsonData[i][12]);
                if (humidity.position == 0) {
                  reelList.frontComponentList.push(humidity);
                } else if (humidity.position == 1) {
                  reelList.oppositeComponentList.push(humidity);
                }
              } else if (col2 == 3) {
                let desiccant = new Desiccant();
                desiccant.code = jsonData[i][2];
                desiccant.position = toPosition(jsonData[i][3]);
                desiccant.length = jsonData[i][4];
                desiccant.width = jsonData[i][5];
                desiccant.x = jsonData[i][6];
                desiccant.y = jsonData[i][7];
                desiccant.angle = jsonData[i][8];
                desiccant.weight = jsonData[i][9];
                desiccant.desiccantType = jsonData[i][10];
                desiccant.desiccantColor = jsonData[i][11];
                desiccant.desiccantColorHeight = jsonData[i][12];
                desiccant.picName = toImg(jsonData[i][13]);
                if (desiccant.position == 0) {
                  reelList.frontComponentList.push(desiccant);
                } else if (desiccant.position == 1) {
                  reelList.oppositeComponentList.push(desiccant);
                }
              }
            } else if (col1 == 1) {
              //包装袋信息
              if (!jsonData[i][2]) {
                throw new Error("必填项包装袋料号不能为空");
              }
              packageConfig.bagType = toBagType(jsonData[i][1]);
              packageConfig.bagCode = jsonData[i][2];
              packageConfig.bagWidth = jsonData[i][3];
              packageConfig.bagHeigh = jsonData[i][4];
              packageConfig.hasLogo = toBool(jsonData[i][5]);
              packageConfig.hasESD = toBool(jsonData[i][6]);
              packageConfig.esdMaterialCode = jsonData[i][7];
              packageConfig.esdModel = jsonData[i][8];
              packageConfig.esdSizeInBag = toPosition(jsonData[i][9]);
              packageConfig.esdPositionX = jsonData[i][10];
              packageConfig.esdPositionY = jsonData[i][11];
              packageConfig.esdPositionR = jsonData[i][12];
              packageConfig.reelInMBBUpSide = toPosition(jsonData[i][13]);
              packageConfig.mbBinReelAngle = jsonData[i][14];
              packageConfig.isNeedSealingVacuum = toBool(jsonData[i][15]);
              packageConfig.mbbVacuumTime = jsonData[i][16];
              packageConfig.hasSealing = toBool(jsonData[i][17]);
              packageConfig.ngSealing = toBool(jsonData[i][18]);
              packageConfig.mbbSealingTime = jsonData[i][19];
              packageConfig.mbbSealingTimes = jsonData[i][20];
              packageConfig.mbbSealingLineDistance = jsonData[i][21];
              packageConfig.mbbCoolingTime = jsonData[i][22];
              packageConfig.isNeedSealingNitrogen = toBool(jsonData[i][23]);
              packageConfig.isNeedHeliumTest = toBool(jsonData[i][24]);
              packageConfig.frontImg = toImg(jsonData[i][25]);
              packageConfig.oppositeImg = toImg(jsonData[i][26]);
            } else if (col1 == 2) {
              if (!jsonData[i][2]) {
                continue;
              }
              if (col2 == 0) {
                //标签信息
                let label = parseLable(jsonData, i);
                if (jsonData[i][4] == "正面") {
                  packageConfig.packageList[0].frontComponentList.push(label);
                } else if (jsonData[i][4] == "反面") {
                  packageConfig.packageList[0].oppositeComponentList.push(
                    label
                  );
                }
              } else if (col2 == 1) {
                let prolabel = parseProlabel(jsonData, i);
                if (jsonData[i][4] == "正面") {
                  packageConfig.packageList[0].frontComponentList.push(
                    prolabel
                  );
                } else if (jsonData[i][4] == "反面") {
                  packageConfig.packageList[0].oppositeComponentList.push(
                    prolabel
                  );
                }
              }
            } else if (col1 == 3) {
              if (!jsonData[i][2]) {
                throw new Error("必填项内盒料号不能为空");
              }
              innerBox.boxType = jsonData[i][1];
              innerBox.boxMaterialCode = jsonData[i][2];
              innerBox.boxLength = jsonData[i][3];
              innerBox.boxWidth = jsonData[i][4];
              innerBox.boxHeigh = jsonData[i][5];
              innerBox.bagsPerBox = jsonData[i][6];
              innerBox.binsPerBox = jsonData[i][7];
              innerBox.sealingMaterialCode = jsonData[i][8];
              innerBox.sealingSpec = jsonData[i][9];
              innerBox.sealingMode = jsonData[i][10];
              innerBox.hasQASeals = toBool(jsonData[i][11]);
              innerBox.qaSealsMaterialCode = jsonData[i][12];
              innerBox.qaSealsType = jsonData[i][13];
              innerBox.qaSealsLenth = jsonData[i][14];
              innerBox.qaSealsWidth = jsonData[i][15];
              innerBox.qaSealsPositionSize = toPosition(jsonData[i][16]);
              innerBox.qaSealsPositionX = jsonData[i][17];
              innerBox.qaSealsPositionY = jsonData[i][18];
              innerBox.hasRidingStamps = toBool(jsonData[i][19]);
              innerBox.ridingStampsMaterialCode = jsonData[i][20];
              innerBox.ridingStampsType = jsonData[i][21];
              innerBox.ridingStampingPosition = toPosition(jsonData[i][22]);
              innerBox.bubbleBagStamp = toBool(jsonData[i][23]);
              innerBox.bubbleBagMaterialCode = jsonData[i][24];
              innerBox.bubbleBagModel = jsonData[i][25];
              innerBox.bubbleBagWidth = jsonData[i][26];
              innerBox.bubbleBagLenght = jsonData[i][27];
              innerBox.hasBoxSprayCodes = toBool(jsonData[i][28]);
              innerBox.sprayCodesSide = toPosition(jsonData[i][29]);
              innerBox.sprayCodesX = jsonData[i][30];
              innerBox.sprayCodesY = jsonData[i][31];
              innerBox.sprayCodesR = jsonData[i][32];
            } else if (col1 == 4) {
              if (!jsonData[i][2]) {
                continue;
              }
              if (col2 == 0) {
                //标签信息
                let label = parseLable(jsonData, i);

                if (jsonData[i][4] == "前面") {
                  innerBox.boxList[0].frontComponentList.push(label);
                } else if (jsonData[i][4] == "后面") {
                  innerBox.boxList[0].backComponentList.push(label);
                } else if (jsonData[i][4] == "左面") {
                  innerBox.boxList[0].leftComponentList.push(label);
                } else if (jsonData[i][4] == "右面") {
                  innerBox.boxList[0].downComponentList.push(label);
                } else if (jsonData[i][4] == "顶面") {
                  innerBox.boxList[0].upComponentList.push(label);
                } else if (jsonData[i][4] == "底面") {
                  innerBox.boxList[0].downComponentList.push(label);
                }
              } else if (col2 == 1) {
                let prolabel = parseProlabel(jsonData, i);
                if (jsonData[i][4] == "前面") {
                  innerBox.boxList[0].frontComponentList.push(prolabel);
                } else if (jsonData[i][4] == "后面") {
                  innerBox.boxList[0].backComponentList.push(prolabel);
                } else if (jsonData[i][4] == "左面") {
                  innerBox.boxList[0].leftComponentList.push(prolabel);
                } else if (jsonData[i][4] == "右面") {
                  innerBox.boxList[0].downComponentList.push(prolabel);
                } else if (jsonData[i][4] == "顶面") {
                  innerBox.boxList[0].upComponentList.push(prolabel);
                } else if (jsonData[i][4] == "底面") {
                  innerBox.boxList[0].downComponentList.push(prolabel);
                }
              }
            }
          }
          result.push(jsonStore);
        }
        resolve(result);
      } catch (e) {
        console.error(e);
        ElMessage({
          message: "解析失败--> " + e,
          type: "error",
          showClose: true,
          duration: 5000,
        });
        reject(e);
      }
    };
  });
}

function parseLable(jsonData, i) {
  let label = new Label();
  label.code = jsonData[i][2];
  label.reelType = 1;
  label.mergeType = toReel(jsonData[i][3]);
  label.isProLabel = false;
  label.position = toPosition(jsonData[i][4]);
  label.length = jsonData[i][5];
  label.width = jsonData[i][6];
  label.x = jsonData[i][7];
  label.y = jsonData[i][8];
  label.angle = jsonData[i][9];
  label.labelTemplate = jsonData[i][10];
  label.qaStamp = toBool(jsonData[i][11]);
  label.qaStampCode = jsonData[i][12];
  label.qaStampX = jsonData[i][13];
  label.qaStampY = jsonData[i][14];
  label.qaStampAngle = jsonData[i][15];
  label.qaStampType = jsonData[i][16];
  label.picName = toImg(jsonData[i][17]);

  return label;
}

function parseProlabel(jsonData, i) {
  let prolabel = new ProLabel();
  prolabel.code = jsonData[i][2];
  prolabel.reelType = 1;
  prolabel.mergeType = toReel(jsonData[i][3]);
  prolabel.isProLabel = true;
  prolabel.position = toPosition(jsonData[i][4]);
  prolabel.proType = toProlabel(jsonData[i][5]);
  prolabel.length = jsonData[i][6];
  prolabel.width = jsonData[i][7];
  prolabel.x = jsonData[i][8];
  prolabel.y = jsonData[i][9];
  prolabel.angle = jsonData[i][10];
  prolabel.labelTemplate = jsonData[i][11];
  prolabel.qaStamp = toBool(jsonData[i][12]);
  prolabel.qaStampCode = jsonData[i][13];
  prolabel.qaStampX = jsonData[i][14];
  prolabel.qaStampY = jsonData[i][15];
  prolabel.qaStampAngle = jsonData[i][16];
  prolabel.qaStampType = jsonData[i][17];
  prolabel.isNotNeedLabelForMSL1 = toBool(jsonData[i][18]);
  prolabel.mslPrintMethod = toPrintMethod(jsonData[i][19]);
  prolabel.mslCustomStr = jsonData[i][20];
  prolabel.picName = toImg(jsonData[i][21]);
  return prolabel;
}

function toBool(val) {
  return val === "是" ? true : false;
}

function toPosition(val) {
  let res = null;
  switch (val) {
    case "正面":
      res = 0;
      break;
    case "反面":
      res = 1;
      break;
    case "前面":
      res = 3;
      break;
    case "后面":
      res = 5;
      break;
    case "左面":
      res = 7;
      break;
    case "右面":
      res = 6;
      break;
    case "顶面":
      res = 2;
      break;
    case "底面":
      res = 4;
      break;
  }
  return res;
}

function toReel(val) {
  if (val == "整盘") {
    return 1;
  } else if (val == "合并盘") {
    return 2;
  } else if (val == "零盘") {
    return 3;
  } else {
    return 0;
  }
}

function toProlabel(val) {
  if (val == "湿度敏感标签") {
    return 1;
  } else if (val == "ROHS标签") {
    return 2;
  } else if ((val = "ESD静电贴")) {
    return 3;
  }
}

function toBagType(val) {
  if (val == "铝箔袋") {
    return 0;
  } else if (val == "透明带") {
    return 1;
  } else {
    return null;
  }
}

let scattered = {
  protectiveTape: "保护带",
  foam: "泡棉",
};
let scaKey = Object.keys(scattered);
let scaVal = Object.values(scattered);

function toScattered(val) {
  let res = [];
  let strArr = val?.split("+") ?? [];
  strArr.forEach((item) => {
    let index = scaVal.indexOf(item);
    if (index > -1) {
      res.push(scaKey[index]);
    }
  });
  return res;
}

function toPrintMethod(val) {
  if (val == "不喷涂") {
    return 0;
  } else if (val == "日期") {
    return 1;
  } else if (val == "自定义内容") {
    return 2;
  }
}

function toImg(val) {
  return (
    getEnvConfig.VITE_BASE_URL.replace("api", "") + "Upload/Material/" + val
  );
}
